package com.zheng.classloader;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 *  @author: zheng
 *  @Date: 2020-06-23 16:30
 *  @Description:
 */
public class MyClassLoader extends ClassLoader {


    @Override
    protected Class<?> findClass(String classPath) {
        try (InputStream in = new FileInputStream(classPath)) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int i = 0;
            while ((i = in.read()) != -1) {
                out.write(i);
            }
            byte[] byteArray = out.toByteArray();
            return defineClass(byteArray, 0, byteArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static Object getMyClass(String path) throws IllegalAccessException, InstantiationException {
        MyClassLoader myClassLoader=new MyClassLoader();
        Class<?> clazz = myClassLoader.findClass(path);
        Object newInstance = clazz.newInstance();
        return newInstance;
    }
}
